import axios from 'axios'
// import { MessageBox, Message } from 'element-ui'
import store from '@/store'
import router from '@/router/index'
import { Message } from 'element-ui'
import { getTimer } from './auth'

// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000 // request timeout
})

const timer = 28800000

// 请求拦截器
service.interceptors.request.use(
  config => {
    // console.log('这里是请求拦截器config', config)
    // do something before request is sent

    if (store.getters.token) {
      // 这里是token过期的主动处理
      if (new Date().getTime() - getTimer() > timer) {
        store.dispatch('user/logout')
        router.push('/login')
        Message.error('这是前端规定token过期')
        return Promise.reject('登录失效，前端让你退出')
      }
      // 登入与注册不能携带token 故而去掉
      if (config.url !== '/auth/local/register' && config.url !== '/auth/local') {
        config.headers.Authorization = 'Bearer ' + store.state.user.token
      }
    }
    return config
  },
  error => {
    // do something with request error
    // console.log(error, '请求失败') // for debug
    return Promise.reject(error)
  }
)

// 响应拦截器  -- 接收时的错误处理已完成
service.interceptors.response.use(
  (response) => {
    // console.log(response)
    if (response.status === 200) {
      // 数据请求成功
      if (response.config.method !== 'get' && response.config.method !== 'GET') {
        Message.success(response.statusText)
      }
      return response
    } else {
      // 数据错误
      console.log(response, '数据错误')
      Message.error(response.statusText)
      return response
    }
  },
  // 网络错误 --- 后端规定的token失效处理
  (error) => {
    console.log(error, '网络错误')
    // console.dir(error)
    // 如果符合token失效规则，则给予退出登录
    if (error.response.status === 401 && error.response) {
      store.dispatch('user/logout')
      router.push('/login')
      Message.error('这是后台规定token过期')
    } else {
      Message.error(error.response.data.message)
    }
    return Promise.reject(error)
  })
export default service
